package utils.global.jwt;

import cn.hutool.core.util.IdUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.HashMap;

@Data
@Slf4j
public class JwtUtils {

    @Autowired
    JwtProperties jwtProperties;

    private String version;

    public JwtUtils() {
        version = IdUtil.randomUUID();
    }

    /* 生成token */
    public String createToken(HashMap<String, String> params, Long expectedTime) {

        JWTCreator.Builder builder = JWT.create();

        if (expectedTime != -1) {
            builder.withExpiresAt(new Date(expectedTime));
        }

        if (params != null) {
            params.forEach(builder::withClaim);
        }

        builder.withClaim("version", version);

        if (jwtProperties.getSalt() == null || "".equals(jwtProperties.getSalt())) {
            return builder.sign(Algorithm.HMAC256(IdUtil.randomUUID()));
        } else
            return builder.sign(Algorithm.HMAC256(jwtProperties.getSalt()));
    }

    public String createToken(Long expectedTime) {

        return createToken(null, expectedTime);

    }

    public DecodedJWT verify(String toKey) {

        if (toKey == null || "".equals(toKey)) {
            log.warn("token 为空");
            return null;
        }

        try {
            JWTVerifier build = JWT.require(Algorithm.HMAC256(jwtProperties.getSalt())).build();

            DecodedJWT verify = build.verify(toKey);

            return verify;
        } catch (IllegalArgumentException | JWTVerificationException e) {

            e.printStackTrace();

            return null;
        }
    }
}
